package org.seedltd.upms.service.impl.common;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.seedltd.log.OptLog;
import org.seedltd.log.properties.StoreType;
import org.seedltd.log.service.LogService;
import org.seedltd.mail.properties.CustomsMailProperties;
import org.seedltd.mail.service.MailConfigService;
import org.seedltd.springsecurity.callback.LoginCallback;
import org.seedltd.upms.constant.GlobalConst;
import org.seedltd.upms.model.detection.vo.DetectionMpConfigVO;
import org.seedltd.upms.service.common.BaseCommonServer;
import org.seedltd.upms.service.detection.DetectionMpConfigService;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import lombok.AllArgsConstructor;

@AllArgsConstructor
@Service("baseCommonServer")
public class BaseCommonServerImpl implements BaseCommonServer, MailConfigService, LoginCallback {

    private final DetectionMpConfigService detectionMpConfigService;
    private final LogService logService;

    @Override
    public List<CustomsMailProperties> getMailProperties() {
        DetectionMpConfigVO config = detectionMpConfigService.findById(1L);

        CustomsMailProperties customsMailProperties = new CustomsMailProperties();
        customsMailProperties.setHost(config.getMailHost());
        customsMailProperties.setPort(Integer.valueOf(config.getMailPort()));
        customsMailProperties.setUsername(config.getUsername());
        customsMailProperties.setPassword(config.getPass());
        customsMailProperties.setDefaultEncoding(StandardCharsets.UTF_8);
        customsMailProperties.addProperties("mail.smtp.ssl.enable",
            GlobalConst.YES.equals(config.getSslEnable()) ? "true" : "false");

        return Lists.newArrayList(customsMailProperties);
    }

    @Override
    public void success(HttpServletRequest request, Long userId, String accessToken) {
        OptLog optLog = OptLog.getOptLog(request, OptLog.OptType.LOGIN, StoreType.db);
        optLog.setFinishTime(LocalDateTime.now());
        logService.addLog(optLog);
    }
}
